package com.eascs.banknet.boc.service.trans;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.BOC001Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.boc001.BOC001Bean;
import com.eascs.banknet.boc.vo.boc001.BOC001Element;
import com.eascs.banknet.boc.vo.boc001.BOC001Root;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;
/**
 * 中行贷款申请提交
 * @author user 
 *
 */
@Service("boc001Service")
public class BOC001Service extends BOCAbstractService {
	private static final Logger logger = LoggerFactory.getLogger(BOC001Service.class);
	
	@Autowired
	private BOC001Dao boc001Dao;
	
	private String startId;
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("001");
		logEntity.setTypeName("贷款申请");
		logEntity.setStartTime(new Date());
		return logEntity;
	}

	@Override
	public Map<String, String> dowork() {
		//不管成功or失败，都要记录当前执行startId，用于下一次轮询开始的标记，若没有扫描到数据则重置startId重新开始
		String id = "";	//申请编号
		String loanapplyNo = "";
		LogEntity logEntity = initLogData();
		try {
			logger.info("贷款申请开始......");
			/**
			 * 查询数据，组装请求xml
			 */
			BOC001Element element = null;
			while(null == element){
				//查询贷款单数据
				BOC001Bean bean = boc001Dao.queryData(startId);
				if(null == bean){
					startId = null;
					logger.info("贷款申请，没有符合条件的数据");
					return null;
				}
				id = bean.getAPPNO();
				loanapplyNo = loanapplyDao.getLoanapplyNoByAppno(id);
				startId = id;
				//查询贷款人CRM资料，若资料不完整则记录日志并跳到下个贷款单
				element = boc001Dao.joinCrmInfo(bean);
				if(null == element){
					logger.error("申请人客户信息不完整,appno:[{}], customer_id:[{}]", id, bean.getCustomerId());
					logService.writeLog(initLogData(), id, LogEntity.RESULT_TYPE_ERROR, "客户资料不完整，请检查客户和门店信息");
				}else{
					String checkMsg = boc001Dao.checkElement(element);
					if(StringUtil.hasText(checkMsg)){
						logger.error("申请人信息不完整,appno:[{}], checkMsg:[{}]", id, checkMsg);
						logService.writeLog(initLogData(), id, LogEntity.RESULT_TYPE_ERROR, checkMsg);
						element = null;
					}
				}
			}
			//中行测试环境只能用这个
			if("26.127.253.48".equals(bocUtil.getBocSocketInfo().getHref())){
				element.setCCTPERTRN_PERFSTNM("红丽");
				element.setCCTPERTRN_PERLSTNM("杨");
				element.setCCTPERTRN_CBICERNO("412926197205234920");
			}
			//组装请求的xml消息
			BOC001Root root = new BOC001Root();
			root.getBody().setElement(element);
			//保存xml文件到ftp服务器
			String xml = XmlHelp.convertToXml(root);
			XmlHelp.createXml("001" + "(" + loanapplyNo + ")", loanapplyNo + "&" + xml, "BOC001RQ", bocUtil.getEaFtpInfo());
			
			/*
			 * 调用中行接口
			 */
			logger.info("组装请求数据完成，开始调用中行001接口, appno:[{}]:{},xml:{}", id , xml);	
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(), "001", null, xml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行001接口返回数据为空！");
				throw new Exception("中行001接口返回数据为空");
			}
			logger.info("中行001接口返回xml完成, returnXml：{}", returnXml);
			
			/*
			 * 解析返回xml，保存数据
			 */
			XmlHelp.createXml("001"+"("+loanapplyNo+")",returnXml,"BOC001RS", bocUtil.getEaFtpInfo());	
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			Element body = rsRoot.getChild("BODY");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				String note = head.getChildText("NOTE");
				if(StringUtil.isEmpty(note)){
					//NOTE内容包含换行时获取不到内容，用字符串截取
					note = StringUtils.substringBetween(returnXml, "<NOTE>", "</NOTE>");
				}
				throw new Exception(note);
			}
			Element trn = body.getChild("OUTPUT");
			String appno = trn.getChildText("APPNO");
			boc001Dao.updateInfo(loanapplyNo, appno);
			logger.info("贷款申请调用成功,appno:[{}]", appno);
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_SUCCESS, null);
		} catch (Exception e) {
			logger.error("贷款申请出现异常，appno：[{}]，errMsg：[{}]", id,  e.getMessage());
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
}
